<template>
  <div>
    <el-row>
      <el-col>
        <my-form
          :formOptions="findFormOptions"
          :isInline="true"
          :isSearch="true"
          @sureSubmit="findTableData"
        >
          <template #bottom_button>
            <el-button
              icon="el-icon-refresh"
              size="mini"
              type="primary"
              @click="reset"
              >重置</el-button
            >
          </template>
        </my-form>
      </el-col>
    </el-row>
    <el-row type="flex" justify="end">
      <el-col :span="2">
        <el-popconfirm
          confirm-button-text="审核通过"
          cancel-button-text="审核不通过"
          confirm-button-type="success"
          cancel-button-type="danger"
          @confirm="check_T"
          @cancel="check_F"
          icon="el-icon-info"
          icon-color="red"
          title="请选择操作"
        >
          <el-button
            slot="reference"
            icon="el-icon-coordinate"
            type="primary"
            size="mini"
            v-if="nowRoot != '教师'"
            >批量审核</el-button
          >
        </el-popconfirm>
      </el-col>
      <el-col :span="10">
        <el-button
          size="mini"
          @click="add"
          icon="el-icon-circle-plus"
          type="primary"
          v-if="nowRoot === '教师'"
          >新增</el-button
        >

        <el-upload
          class="upload-demo"
          ref="excelUpload"
          action="http://localhost:8080/api/SciThesis/uploadExcel"
          :before-upload="onBeforeUpload"
          :on-success="uploadSuccess"
          :show-file-list="false"
        >
          <el-button
            icon="el-icon-upload"
            type="primary"
            size="mini"
            v-if="nowRoot === '教师'"
            >导入数据表格</el-button
          >
        </el-upload>
        <el-button
          size="mini"
          icon="el-icon-download"
          type="primary"
          @click="downloadExample"
          >下载导入样例xlsx表格</el-button
        >
        <el-button
          size="mini"
          icon="el-icon-download"
          type="primary"
          @click="downloadExcel"
          >导出表格</el-button
        >
      </el-col>
    </el-row>
    <el-row>
      <el-col>
        <my-table
          :hasBorder="true"
          :hasIndex="true"
          :hasPagination="true"
          :hasStripe="true"
          :hasSelection="true"
          :tableColumnOptions="tableColumnOptions"
          :tableData="tableData"
          
          :sortRule="{prop: 'thesisSstate', order: 'ascending'}"
          @selectionChange="selectionChange"
        >
          <template #thesisClass="{ data }">
            <span>{{ data.thesisClass === "1" ? "期刊" : "会议" }}</span>
          </template>
          <template #thesisSub="{ data }">
            <span>{{ data.thesisSub === "1" ? "自然项目" : "人文项目" }}</span>
          </template>
          <template #thesisTime="{ data }">
            <span>{{ (data.thesisTime + "").slice(0, 10) }}</span>
          </template>
          <template #thesisSstate="{ data }">
            <span>{{
              data.thesisSstate == "-1"
                ? "未通过"
                : data.thesisSstate == "0"
                ? "未审核"
                : data.thesisSstate == "1"
                ? "院级通过"
                : "校级通过"
            }}</span>
          </template>
          <template #operation="{ data }">
            <el-button type="text" @click="look(data)">查看</el-button>
            <el-button
              type="text"
              @click="update(data)"
              v-if="nowRoot === '教师'"
              >编辑</el-button
            >

            <el-button
              type="text"
              @click="remove(data)"
              v-if="nowRoot === '教师'"
              >删除</el-button
            >
          </template>
        </my-table>
      </el-col>
    </el-row>
    <el-row>
      <p>注：①教师每次进行编辑时，请重新选择级别！！！！</p>
      <p>②管理层进行单个审核时，同批量审核操作步骤</p>
      <p>③如果有附件需要，请先上传附件(仅支持一个文件)，再点击提交</p>
    </el-row>
    <my-dialog :dialogVisible.sync="infoDialog" :title="infoTitle">
      <template #content>
        <my-form
          :form="isAddInfo ? copyForm : form"
          :formOptions="infoFormOptions"
          :rules="infoRules"
          @sureSubmit="infoFormSubmit"
          ref="infoForm"
        >
          <template #thesisPerson="{ data }">
            <el-autocomplete
              v-model="user1"
              :fetch-suggestions="querySearch"
              placeholder="请输入内容"
              style="width: 160px"
              @select="handleSelect_person"
            ></el-autocomplete>
          </template>
          <template #thesisGrade>
            <el-select
              v-model="test1"
              placeholder="请选择"
              style="width: 187px"
              @change="handleLevel1"
            >
              <el-option
                v-for="item in level1"
                :key="item.lnormalName"
                :label="item.lnormalName"
                :value="item.lnormalName"
              >
              </el-option>
            </el-select>
          </template>
          <template #bottom_button>
            <el-upload
              class="upload-files"
              ref="filesUpload"
              action="http://localhost:8080/api/SciThesis/uploadFile"
              :before-upload="onBeforeUploadFile"
              :data="uploadmsg"
              :multiple="true"
              :limit="1"
              :show-file-list="true"
              :auto-upload="false"
            >
              <el-button type="success" icon="el-icon-upload" size="mini"
                >上传附件(仅支持一个文件)</el-button
              >
            </el-upload>
          </template>
        </my-form>
      </template>
    </my-dialog>
    <my-dialog :dialogVisible.sync="lookDialog">
      <template #content>
        <my-description :border="false" :list="list">
          <template #bottom>
            下载附件
            <el-link
              type="primary"
              v-for="(item, index) in files"
              :key="item"
              @click="downLoadFiles(item)"
              >{{ item }}</el-link
            >
          </template>
        </my-description>
      </template>
    </my-dialog>
  </div>
</template>

<script>
import {projectCate,getLabelByModel,thesisCategory, getModelByLabel} from "@/utils/metaInfo"
import myForm from "@/components/myForm.vue";
import myTable from "@/components/myTable.vue";
import myDialog from "@/components/myDialog.vue";
import myDescription from "@/components/myDescription.vue";
import {
  A_tableData,
  A_add,
  A_update,
  A_remove,
  A_check_T,
  A_check_F,
  A_downLoadExcel,
  A_getFile,
  A_getLevel1,
  A_downLoadExample,
} from "@/api/resultMange/scientificPayoffs/researchPaper";
import {
  E_beforeUpload,
  E_uploadSuccess,
  E_downloadExcel,
} from "@/utils/aboutExcel";
import cloneDeep from "lodash/cloneDeep";
import { A_downLoadFile, A_showFile, A_getKey } from "@/utils/aboutFile";
import { mapState } from "vuex";
import { A_getUserList } from "@/utils/aboutUsers";
export default {
  name: "researchPaper",
  inject: ["reload"],
  data() {
    return {
      findFormOptions: [
        { type: "input", label: "论文卷号", model: "thesisId" },
      ],
      tableColumnOptions: [
        {
          slotName: "thesisSub",
          label: "学科分类",
          prop: "thesisSub",
        },
        {
          label: "标题",
          prop: "thesisTitle",
        },
        {
          label: "期刊名",
          prop: "thesisJournal",
        },
        {
          label: "卷号",
          prop: "thesisId",
        },
        {
          label: "期号",
          prop: "thesisQid",
        },
        {
          label: "成果归属人工号",
          prop: "thesisPerson",
          width: "120",
        },
        {
          label: "成果归属人姓名",
          prop: "name",
          width: "120",
        },
        {
          label: "成果归属单位",
          prop: "thesisWork",
        },
        {
          label: "第一作者单位",
          prop: "thesisFiraututil",
        },
        {
          slotName: "thesisTime",
          label: "发表时间",
          prop: "thesisTime",
          isSlot: true,
        },
        {
          slotName: "thesisClass",
          label: "类别",
          prop: "thesisClass",
        },
        {
          label: "级别",
          prop: "thesisGrade",
        },
        {
          label: "SCI他引",
          prop: "thesisSciy",
        },
        {
          label: "SSCI他引",
          prop: "thesisSsciy",
        },
        {
          label: "HCI他引",
          prop: "thesisAy",
        },
        {
          label: "CSSCI他引",
          prop: "thesisCy",
        },
        {
          label: "科研分值",
          prop: "thesisSorce",
        },
        {
          label: "通讯作者",
          prop: "thesisTperson",
        },
        {
          label: "摘要",
          prop: "thesisZy",
        },
        {
          isSortable: true,
          isSlot: true,
          slotName: "thesisSstate",
          label: "审核状态",
          prop: "thesisSstate",
        },
        {
          label: "操作",
          width: "180",
          isSlot: true,
          slotName: "operation",
          fixed: "right",
        },
      ],
      tableData: [],
      infoDialog: false,
      infoTitle: "编辑操作",
      isAddInfo: false,
      lookDialog: false,
      form: {},
      copyForm: {},
      infoFormOptions: [
        {
          type: "input",
          label: "标题",
          model: "thesisTitle",
        },
        {
          type: "input",
          label: "期刊名",
          model: "thesisJournal",
        },
        {
          type: "input",
          label: "卷号",
          model: "thesisId",
        },
        {
          type: "input",
          label: "期号",
          model: "thesisQid",
        },
        {
          type: "radio",
          label: "学科分类",
          model: "thesisSub",
          width: 500,
          options: projectCate,
        },
         {
          type: "radio",
          label: "类别",
          model: "thesisClass",
          width: 500,
          options: thesisCategory,
        },
        {
          type: "slot",
          slotName: "thesisPerson",
          label: "成果归属人工号",
          model: "thesisPerson",
        },
        {
          type: "input",
          label: "成果归属单位",
          model: "thesisWork",
        },
        {
          type: "slot",
          slotName: "thesisGrade",
          label: "级别",
          model: "thesisGrade",
        },
       
        {
          type: "input",
          label: "第一作者单位",
          model: "thesisFiraututil",
        },
        {
          type: "input",
          label: "SCI他引",
          model: "thesisSciy",
        },
        {
          type: "input",
          label: "SSCI他引",
          model: "thesisSsciy",
        },
        {
          type: "input",
          label: "HCI他引",
          model: "thesisAy",
        },
        {
          type: "input",
          label: "CSSCI他引",
          model: "thesisCy",
        },
        {
          type: "date",
          label: "发表时间",
          model: "thesisTime",
          width: 195,
        },
        {
          type: "input",
          label: "通讯作者",
          model: "thesisTperson",
        },
        {
          type: "textarea",
          label: "摘要",
          model: "thesisZy",
          width: 550,
        },
      ],
      infoRules: {
        thesisSub: [{ required: true, message: "请选择学科分类" }],
        thesisTitle: [{ required: true, message: "请输入标题" }],
        thesisJournal: [{ required: true, message: "请输入期刊名" }],
        thesisId: [{ required: true, message: "请输入卷号" }],
        thesisQid: [{ required: true, message: "请输入期号" }],
        thesisPerson: [{ required: true, message: "请输入成果归属人工号" }],
        thesisWork: [{ required: true, message: "请输入成果归属单位" }],
        thesisFiraututil: [{ required: true, message: "请输入第一作者单位" }],
        thesisTime: [{ required: true, message: "请选择发表时间" }],
        thesisGrade: [{ required: true, message: "请选择类别" }],
        thesisClass: [{ required: true, message: "请选择级别" }],
      },
      multipleSelection: [],
      uploadmsg: {},
      files: [],
      level1: [],
      test1: "",
      user1: "",
      user_list: null,
      fileKey: 0,
    };
  },
  components: {
    myForm,
    myTable,
    myDialog,
    myDescription,
  },
  created() {
    this.getTableData();
    this.getLevel1();
  },
  methods: {
    async getUserList() {
      let result = await A_getUserList();
      result.forEach((item) => {
        const value = item.userId + " : " + item.userName;
        item.value = value;
      });
      this.user_list = result;
    },
    async findTableData(data) {
      let result = await A_tableData(data);
      this.tableData = cloneDeep(result);
      // if (result.code === 1) {

      // } else {
      //   this.$message({ type: "error", message: "信息获取失败" });
      // }
    },
    async getTableData() {
      let result = await A_tableData({});
      this.tableData = cloneDeep(result);
      // if (result.code === 1) {

      // } else {
      //   this.$message({ type: "error", message: "信息获取失败" });
      // }
      this.tableData.forEach(item=>{
          item.thesisSub = getLabelByModel(item.thesisSub,projectCate)
          item.thesisClass = getLabelByModel(item.thesisClass,thesisCategory)
      })   

    },
    async reset() {
      let result = await A_tableData({});
      this.tableData = cloneDeep(result);
      // if (result.code === 1) {

      // } else {
      //   this.$message({ type: "error", message: "信息获取失败" });
      // }
    },
    selectionChange(data) {
      this.multipleSelection = cloneDeep(data);
    },
    async look(data) {
      this.form = cloneDeep(data);
      this.lookDialog = true;
      const { thesisKey } = data;
      let res = await A_getFile(thesisKey);
      if (res.code === 1) {
        this.files = res.data;
      } else {
        this.$message({ type: "error", message: "出错啦" });
      }
    },
    add() {
      this.isAddInfo = true;
      this.infoDialog = true;
      this.getUserList();
    },
    update(data) {
      this.isAddInfo = false;
      this.infoDialog = true;
      this.form = cloneDeep(data);
      this.getUserList();
    },
    remove(data) {
      this.$confirm("你确定要删除该数据吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const { thesisKey } = data;
          let res = await A_remove(thesisKey);
          if (res.code === 1) {
            this.$message({ type: "success", message: res.data });
            this.reload();
          } else {
            this.$message({ type: "error", message: res.msg });
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    async check_T() {
      if (this.multipleSelection.length > 0) {
        let res = await A_check_T(this.downloadExcelData);
        if (res.code === 1) {
          this.$message({ type: "success", message: res.data });
          this.reload();
        } else {
          this.$message({ type: "error", message: res.msg });
        }
      } else {
        this.$message.warning("请选择数据");
      }
    },
    async check_F() {
      if (this.multipleSelection.length > 0) {
        let res = await A_check_F(this.downloadExcelData);
        if (res.code === 1) {
          this.$message({ type: "success", message: res.data });
          this.reload();
        } else {
          this.$message({ type: "error", message: res.msg });
        }
      } else {
        this.$message.warning("请选择数据");
      }
    },
    async infoFormSubmit(data) {
      data.thesisSub = getModelByLabel(data.thesisSub,projectCate)
      data.thesisClass = getModelByLabel(data.thesisClass,thesisCategory)
      if (this.isAddInfo) {
        let res = await A_add(data);
        if (res.code === 1) {
          await this.getFileKey();
          await this.$refs.filesUpload.submit();
          this.$message({ type: "success", message: res.data });
          this.reload();
        } else {
          this.$message({ type: "error", message: res.msg });
        }
      } else {
        let res = await A_update(data);
        if (res.code === 1) {
          await this.$refs.filesUpload.submit();
          this.$message({ type: "success", message: res.data });

          this.reload();
        } else {
          this.$message({ type: "error", message: res.msg });
        }
      }
    },
    onBeforeUpload(file) {
      return E_beforeUpload(file);
    },
    uploadSuccess(res, file, flieist) {
      E_uploadSuccess(res);
      this.reload();
    },
    downloadExcel() {
      if (this.multipleSelection.length > 0) {
        E_downloadExcel(this.downloadExcelData).then(
          () => {
            A_downLoadExcel().then(
              (res) => {
                const url = window.URL.createObjectURL(new Blob([res]));
                const link = document.createElement("a");
                link.href = url;
                link.setAttribute("download", "科研论文.xls");
                document.body.appendChild(link);
                link.click();
              },
              () => {
                this.$message({ type: "error", message: "出错了" });
              }
            );
          },
          () => {
            this.$message({ type: "error", message: "出错了" });
          }
        );
      } else {
        this.$message({ type: "warning", message: "请选择要导出的数据" });
      }
    },
    downloadExample() {
      A_downLoadExample().then(
        (res) => {
          const url = window.URL.createObjectURL(new Blob([res]));
          const link = document.createElement("a");
          link.href = url;
          link.setAttribute("download", "导入数据样例表.xls");
          document.body.appendChild(link);
          link.click();
        },
        () => {
          this.$message({ type: "error", message: "出错了" });
        }
      );
    },
    async onBeforeUploadFile(file) {
      if (this.isAddInfo) {
        this.uploadmsg = {
          articalTcatogory: file.name,
          articalCatogory: 3,
          articalId: this.fileKey,
        };
      } else {
        const { thesisKey } = this.form;
        this.uploadmsg = {
          articalTcatogory: file.name,
          articalCatogory: 3,
          articalId: thesisKey,
        };
      }
    },
    async downLoadFiles(file) {
      const { thesisKey } = this.form;
      let result = await A_downLoadFile(3, thesisKey, file);
      A_showFile(file, result);
    },
    async getLevel1() {
      let result = await A_getLevel1();
      this.level1 = result.data;
    },
    handleLevel1(item) {
      this.$refs.infoForm.form.thesisGrade = item;
    },
    async getFileKey() {
      let result = await A_getKey(3);
      this.fileKey = result.data;
    },
    querySearch(queryString, cb) {
      var user_list = this.user_list;
      var results = queryString
        ? user_list.filter(this.createFilter(queryString))
        : user_list;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return (user_list) => {
        return (
          user_list.userName.indexOf(queryString) === 0
        );
      };
    },
    handleSelect_person(item) {
      this.$refs.infoForm.form.thesisPerson = item.userId;
    },
  },
  computed: {
    ...mapState("myInfo", ["nowRoot"]),
    downloadExcelData() {
      let arr = [];
      this.multipleSelection.forEach((item) => {
        arr.push(item.thesisKey);
      });
      return arr;
    },
    list() {
      const {
        thesisTitle,
        thesisJournal,
        thesisId,
        thesisQid,
        thesisSub,
        thesisPerson,
        thesisWork,
        thesisFiraututil,
        thesisTime,
        thesisGrade,
        thesisClass,
        thesisSciy,
        thesisSsciy,
        thesisAy,
        thesisCy,
        thesisSorce,
        thesisTperson,
        thesisZy,
      } = this.form;
      return [
        {
          label: "标题",
          value: thesisTitle,
        },
        {
          label: "期刊名",
          value: thesisJournal,
        },
        {
          label: "卷号",
          value: thesisId,
        },
        {
          label: "期号",
          value: thesisQid,
        },
        {
          label: "学科分类",
          value: thesisSub,
        },
        {
          label: "成果归属人工号",
          value: thesisPerson,
        },
        {
          label: "成果归属单位",
          value: thesisWork,
        },
        {
          label: "第一作者单位",
          value: thesisFiraututil,
        },
        {
          label: "发表时间",
          value:  (thesisTime + "").slice(0, 10),
        },
        {
          label: "类别",
          value: thesisGrade,
        },
        {
          label: "级别",
          value: thesisClass,
        },
        {
          label: "SCI他引",
          value: thesisSciy,
        },
        {
          label: "SSCI他引",
          value: thesisSsciy,
        },
        {
          label: "HCI他引",
          value: thesisAy,
        },
        {
          label: "CSSCI他引",
          value: thesisCy,
        },
        {
          label: "科研分值",
          value: thesisSorce,
        },
        {
          label: "通讯作者",
          value: thesisTperson,
        },
        {
          label: "摘要",
          value: thesisZy,
        },
      ];
    },
  },
};
</script>

<style scoped>
.upload-demo {
  display: inline-block;
  margin: 0 3px;
}
</style>